package com.agriculture.service;

import com.agriculture.entity.GeoDevice;
import com.agriculture.repository.GeoDeviceRepository;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class GeoDeviceService {
    
    @Autowired
    private GeoDeviceRepository deviceRepository;
    
    private final GeometryFactory geometryFactory = new GeometryFactory();
    
    public List<GeoDevice> getAllDevices() {
        return deviceRepository.findAll();
    }
    
    public Optional<GeoDevice> getDeviceById(Integer id) {
        return deviceRepository.findById(id);
    }
    
    public GeoDevice saveDevice(GeoDevice device) {
        return deviceRepository.save(device);
    }
    
    public void deleteDevice(Integer id) {
        deviceRepository.deleteById(id);
    }
    
    public GeoDevice updateDevicePosition(Integer deviceId, Double longitude, Double latitude) {
        Optional<GeoDevice> deviceOpt = deviceRepository.findById(deviceId);
        if (deviceOpt.isPresent()) {
            GeoDevice device = deviceOpt.get();
            Point newPosition = geometryFactory.createPoint(new Coordinate(longitude, latitude));
            device.setCurrentPosition(newPosition);
            return deviceRepository.save(device);
        }
        return null;
    }
    
    public List<GeoDevice> getDevicesByStatus(GeoDevice.DeviceStatus status) {
        return deviceRepository.findByStatus(status);
    }
}